package com.sdry.listener;

import com.sdry.annotation.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * @AUTHOR HACKER
 */
public class ApplicationContextListener implements ApplicationListener<ContextRefreshedEvent> {

	private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationContextListener.class);

	@Override
	public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
		if (null == contextRefreshedEvent.getApplicationContext().getParent()) {
			LOGGER.debug(">>>>> spring init end <<<<<");
			Map<String, Object> baseServices = contextRefreshedEvent.getApplicationContext()
					.getBeansWithAnnotation(BaseService.class);
			for (Object service : baseServices.values()) {
				LOGGER.debug(">>>>> {}.initMapper()", service.getClass().getName());
				try {
					Method initMapper = service.getClass().getMethod("initMapper");
					initMapper.invoke(service);
				} catch (Exception e) {
					LOGGER.error("init initMapper method exception", e);
					e.printStackTrace();
				}
			}
		}
	}

}
